//
// 温湿度传感器
//

package modules

import (
	"time"
	"errors"
	"encoding/binary"
	"adai.design/homemaster/log"
	"math"
)

type HTSensor struct {
	temperature float32
	humidity 	float32

	result chan []byte

	lastTemperature float32
	lastHumidity float32
}

func (ht *HTSensor) handle(data []byte) error {
	ht.temperature = float32(binary.BigEndian.Uint16(data[0:])+50) / 100
	ht.humidity = float32(binary.BigEndian.Uint16(data[2:])+50) / 100
	//log.Info("temperature(%0.1f) humidity(%.0f)", ht.temperature, ht.humidity)

	if ht.temperature < 0.5 || ht.temperature > 50 ||
		ht.humidity <= 0.5 || ht.humidity > 99.9 {
			return nil
	}

	// 刷新属性
	if math.Abs(float64(ht.temperature - ht.lastTemperature)) > 0.15 {
		htService.Temperature.UpdateValue(ht.temperature)
		ht.lastTemperature = ht.temperature
	}

	if math.Abs(float64(ht.humidity - ht.lastHumidity)) > 1.5 {
		htService.Humidity.UpdateValue(int(ht.humidity))
		ht.lastHumidity = ht.humidity
	}

	// 设置温湿度显示
	//SetClockHT(ht.temperature, ht.humidity)
	return nil
}

func (ht *HTSensor) measure() {
	for {
		select {
		case <-time.After(time.Second * 5):
			msg := &MasterMessage{
				pkgType: MasterHTSensor,
				data: []byte{0x01},
			}
			err := masterSendMessage(msg)
			if err != nil {
				log.Notice("ht sensor measure err: %s", err)
			}

		case data, ok := <- ht.result:
			if !ok {
				return
			}
			ht.handle(data)
		}
	}
}

var ht = HTSensor{}

func htObserverMessage(m *MasterMessage) error {
	if len(m.data) != 4 {
		return errors.New("ht measure result format err")
	}

	if ht.result == nil {
		return errors.New("ht measure result channel has been closed")
	}

	ht.result <- m.data
	return nil
}

func StartHTMeasure() {
	addObserver(MasterHTSensor, htObserverMessage)
	ht.result = make(chan []byte, 1)
	go ht.measure()
}

func StopHTMeasure() {
	if ht.result != nil {
		close(ht.result)
		ht.result = nil
	}
	removeObserver(MasterHTSensor)
}





